<template>
  <div class="app-container">
    <el-card v-loading="loading">
      <div style="margin-bottom: 16px;">
        <el-button @click="goBack" icon="ArrowLeft">返回列表</el-button>
      </div>

      <!-- 基本信息头部 -->
      <div class="item-header" style="margin-bottom: 24px;">
        <div style="display: flex; align-items: flex-start; gap: 24px;">
          <!-- 封面图片 -->
          <div class="item-image">
            <el-image
              v-if="coverImage"
              :src="coverImage"
              :preview-src-list="[coverImage]"
              fit="cover"
              style="width: 300px; height: 200px; border-radius: 8px;"
              :preview-teleported="true"
            />
            <div v-else class="image-slot" style="width: 300px; height: 200px; border-radius: 8px; display: flex; flex-direction: column; justify-content: center; align-items: center; background: #f5f7fa; color: #909399;">
              <el-icon style="font-size: 30px;"><Picture /></el-icon>
              <div style="margin-top: 8px;">暂无封面图片</div>
            </div>
          </div>

          <!-- 基本信息 -->
          <div class="item-info" style="flex: 1;">
            <h1 style="font-size: 24px; font-weight: bold; margin-bottom: 16px;">{{ eventInfo.name }}</h1>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">活动分类：</span>
                <span class="value">{{ categoryName || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">所属地区：</span>
                <span class="value">{{ regionName || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">活动地址：</span>
                <span class="value">{{ eventInfo.location || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">主办方：</span>
                <span class="value">{{ eventInfo.organizer || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">开始时间：</span>
                <span class="value">{{ formatDate(eventInfo.startTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">结束时间：</span>
                <span class="value">{{ formatDate(eventInfo.endTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">展示状态：</span>
                <el-tag :type="Number(eventInfo.status) === 1 ? 'success' : 'danger'">
                  {{ Number(eventInfo.status) === 1 ? '启用' : '禁用' }}
                </el-tag>
              </div>

            </div>
          </div>
        </div>
      </div>

      <!-- 详细介绍 -->
      <div class="section" style="margin-bottom: 24px;" v-if="detail.description">
        <h2 class="section-title">详细介绍</h2>
        <div class="section-content">
          <div class="description-content" v-html="formatDescription(detail.description)"></div>
        </div>
      </div>

      <!-- 相关图片 -->
      <div class="section" style="margin-bottom: 24px;" v-if="detail.images && detail.images.length > 0">
        <h2 class="section-title">相关图片</h2>
        <div class="section-content">
          <div class="image-gallery">
            <el-image
              v-for="(image, index) in detail.images"
              :key="index"
              :src="image"
              :preview-src-list="detail.images"
              :initial-index="index"
              fit="cover"
              class="gallery-image"
              :preview-teleported="true"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
        </div>
      </div>

      <!-- 相关视频 -->
      <div class="section" style="margin-bottom: 24px;" v-if="detail.videos && detail.videos.length > 0">
        <h2 class="section-title">相关视频</h2>
        <div class="section-content">
          <div class="video-gallery">
            <div v-for="(video, index) in detail.videos" :key="index" class="video-item">
              <video :src="video" controls style="width: 100%; max-width: 400px; height: 225px;">
                您的浏览器不支持视频播放。
              </video>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup name="EventDetail">
import { ref, onMounted, getCurrentInstance, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getEventDetail } from "@/api/management/event"
import { parseTime } from "@/utils/ruoyi"
import { Picture } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()

const loading = ref(true)
const eventInfo = ref({})
const detail = ref({})
const categoryName = ref('')
const regionName = ref('')

const formatDate = (d) => d ? parseTime(d, '{y}-{m}-{d}') : '-'
const formatDateTime = (d) => d ? parseTime(d, '{y}-{m}-{d} {h}:{i}:{s}') : '-'

const coverImage = computed(() => {
  const img = eventInfo.value?.image
  if (!img) return ''
  if (Array.isArray(img)) return img[0] || ''
  if (typeof img === 'string') {
    if (img.startsWith('[')) {
      try {
        const arr = JSON.parse(img)
        return Array.isArray(arr) ? (arr[0] || '') : ''
      } catch {
        return img
      }
    }
    return img
  }
  return ''
})

const parseMaybeList = (val) => {
  if (!val) return []
  if (Array.isArray(val)) return val
  if (typeof val === 'string') {
    // 去除包裹引号
    const s = val.trim().replace(/^"|"$/g, '')
    if (!s) return []
    if (s.startsWith('[')) {
      try {
        const arr = JSON.parse(s)
        return Array.isArray(arr) ? arr : []
      } catch {
        // fall-through to comma split
      }
    }
    return s.split(',').map(x => x.trim()).filter(Boolean)
  }
  return []
}

const getDetail = async () => {
  try {
    loading.value = true
    const id = route.query.id
    if (!id) {
      proxy.$modal.msgError('活动ID不能为空')
      goBack()
      return
    }
    const res = await getEventDetail(id)
    if (res && res.code === 200 && res.data) {
      // 后端 EventDetailVO 为扁平字段
      const data = res.data
      eventInfo.value = data
      detail.value = {
        description: data.description || '',
        images: parseMaybeList(data.images),
        videos: parseMaybeList(data.videos)
      }
      categoryName.value = data.categoryName || ''
      regionName.value = data.regionName || ''
    } else {
      proxy.$modal.msgError('未获取到活动详情')
    }
  } catch (e) {
    console.error('获取活动详情失败', e)
    proxy.$modal.msgError('获取活动详情失败')
  } finally {
    loading.value = false
  }
}

const goBack = () => router.go(-1)

const formatDescription = (description) => {
  if (!description) return ''
  return description.replace(/\n/g, '<br>')
}

onMounted(getDetail)
watch(() => route.query.id, (n, o) => {
  if (n && n !== o) getDetail()
}, { immediate: false })
</script>

<style scoped>
.app-container { padding: 20px; }
.item-header { border-bottom: 1px solid #ebeef5; padding-bottom: 24px; }
.item-info { padding-left: 24px; }
.info-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }
.info-item { display: flex; align-items: center; }
.label { font-weight: 600; color: #606266; min-width: 80px; }
.value { color: #303133; }
.section { border-bottom: 1px solid #ebeef5; padding-bottom: 24px; }
.section-title { font-size: 18px; font-weight: 600; color: #303133; margin-bottom: 16px; padding-bottom: 8px; border-bottom: 2px solid #409eff; display: inline-block; }
.section-content { color: #606266; line-height: 1.6; }
.description-content { font-size: 14px; line-height: 1.8; }
.image-gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 16px; }
.gallery-image { width: 100%; height: 150px; border-radius: 8px; cursor: pointer; }
.video-gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(400px, 1fr)); gap: 16px; }
.video-item { border-radius: 8px; overflow: hidden; }
.image-slot { display: flex; justify-content: center; align-items: center; width: 100%; height: 100%; background: #f5f7fa; color: #909399; font-size: 30px; }
</style>